//
//  UITextView+EmoticonText.swift
//  表情键盘[练习]
//
//  Created by 鱼龙之梦 on 15/9/12.
//  Copyright © 2015年 panyanzhi. All rights reserved.
//

import UIKit

extension UITextView {
     //MARK:--- 计算型属性，返回完整的表情字符串
    var emoticonText:String {
        let sttrText = attributedText
        var strM = String()
        sttrText.enumerateAttributesInRange(NSRange(location: 0, length: sttrText.length), options: []) { (dict, range, _) -> Void in
            //拿表情图片或者文字
            if let attachment = dict["NSAttachment"] as? YAEmoticonText{
                strM += attachment.chs!
            }else
            {
                let str = (sttrText.string as NSString).substringWithRange(range)
                strM += str
            }
        }
        return strM
    }
///  插入表情符号
    func insertEmoticon(emoticon:YAEmoticon){
        if emoticon.isEmpty {
            return
        }
        if emoticon.isRemove{
            deleteBackward()
            return
        }
        if emoticon.emoji != nil {
            replaceRange(selectedTextRange!, withText: emoticon.emoji!)
            return
        }
        //表情图片
        let imageText = YAEmoticonText.emoticonAttributeText(emoticon, font: font!)
        //1)从textView中取出属性文本
        let strM = NSMutableAttributedString(attributedString: attributedText)
        //2)插入图片文字
        strM.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
        //3)重新设置textView的内容
        //记录当前光标位置
        let range = selectedRange
        
        attributedText = strM
        
        selectedRange = NSRange(location: range.location + 1 , length: 0)
        
        delegate?.textViewDidChange!(self)
    }
}
